import os
import sys
import gdata.docs.data
import gdata.docs.client
import cPickle as pickle

class gCloudBackup:
    """a class to encrypt and backup local data to google data"""
    def __init__(self, localDir, remoteDir):
        self.jobData={'localFileList':[], 'localDirectoryList':[],
                      'remoteFileList':[], 'remoteDirectoryList':[]}
        self.currentJob={}
        self.remoteRoot = '/feeds/default/private/full/folder%3Aroot/contents/-/folder'
        self.localRoot=localDir

        #create a client to google doc
        self.gclient = gdata.docs.client.DocsClient(source='sword_river-cryptogcloud-v1')
        self.gclient.ssl = True  # Force all API requests through HTTPS
        self.gclient.http_client.debug = False  # Set to True for debugging HTTP requests
        self.gclient.ClientLogin('jaycee.li@gmail.com', 'amberqwerty', self.gclient.source)
#        logging.basicConfig(level=logging.WARNING)
#        self.errLog = logging.getLogger('commandProcess')

        # create a datalog file is one doesn't exist
        infoFileName = ('./' + localDir.translate(None, '.').replace('/', '_') +
                        '-' + remoteDir.translate(None, '.').replace('/', '_') + '_' +
                        'infoData.dat')
        currentJobFileName = ('./' + localDir.translate(None, '.').replace('/', '_') +
                              '-' + remoteDir.translate(None, '.').replace('/', '_') + '_' +
                              'currentJob.dat')
        
        # check if the files exist        
        if (os.path.exists(infoFileName) and
            os.path.exists(currentJobFileName)):
            # open and load the two files
            self.infoFile=open(infoFileName, 'rb')
            self.currentJobFile = open(currentJobFileName, 'rb')
            self.jobData = pickle.load(self.infoFile)
            self.currentJob = pickle.load(self.currentJobFile)
            self.infoFile.close()
            self.currentJobFile.close()
            #reopen current job file for write
            self.currentJobFile = open(currentJobFileName, 'wb')
        else:
            #get all the data
            self.__get_local_file_list(self.localRoot)
            self.__get_remote_file_list(self.remoteRoot)
            #open the two files for write
            self.infoFile=open(infoFileName, 'wb')
            self.currentJobFile = open(currentJobFileName, 'wb')
            pickle.dump(self.jobData, self.infoFile)
            self.infoFile.close()
            pickle.dump(self.currentJob, self.currentJobFile)
            self.currentJobFile.close()

    def __get_local_file_list(self, currentDir):
        """ private function to get the file list of the current directory"""
        currentDirFileList = os.listdir(currentDir);
        for line in currentDirFileList:
            dirTest = currentDir + line + "/"
            if (not os.path.isdir(dirTest)):
                line = currentDir + line
                fileSize = os.path.getsize(line)
                fileInfoElement = {'path':line, 'size':fileSize}
                self.jobData['localFileList'].append(fileInfoElement)
            else:
                nextDir = currentDir + line + "/"
                self.jobData['localDirectoryList'].append(nextDir)
                if (os.path.isdir(nextDir)):
                    self.__get_local_file_list(nextDir)
        return 0;

    def __get_remote_file_list(self, currentDir):
        """ private function to get the file list from the google doc server """
        currentDirFileList = self.gclient.GetDocList(uri=currentDir)
        print '.',
        for entry in currentDirFileList.entry:
            path='/'
            pathList=entry.in_folders()
            if len(pathList)!=0:
                for item in pathList:
                    path = path + item.title + '/'
                path = path + entry.title.text
                    
            if entry.GetDocumentType()=="folder":                
                listItem = {'path':path, 'entry':entry}
                self.jobData['remoteDirectoryList'].append(listItem)
                self.__get_remote_file_list(entry.content.src)
            else:
                listItem = {'path':path, 'entry':entry}
                self.jobData['remoteFileList'].append(listItem)
